/* 通用方法 */

/**
 * 提示并跳转
 * @Toast('/pages/test/test'); 提示不跳转
 * @Toast({title: '提示'}, '/pages/index/index'); 提示并跳转
 * @Toast({title: '提示'}, {tab: 1, url: '/pages/index/index'}); 提示并跳转到 tabBar 上
 * @tab=1 跳转至 tabBar 上
 * @tab=2 跳转至非 tabBar 上
 * @tab=3 返回上级页面
 * @tab=4 关闭所有页面跳转至非 tabBar 上
 * @tab=5 关闭当前页面跳转至 tabBar 上
 */
const Toast = function(options, url) {
	if (typeof options == 'string') {
		url = options,
			options = {}
	}
	var title = options.title || '',
		icon = options.icon || 'none',
		duration = options.duration || 1500,
		mask = options.mask || false;
	if (title) uni.showToast({
		title: title,
		icon: icon,
		duration: duration,
		mask: mask
	})
	if (url != undefined) {
		if (typeof url == 'object') {
			var tab = url.tab || 1,
				url = url.url || '';
			switch (tab) {
				case 1:
					setTimeout(function() {
						uni.switchTab({
							url: url
						})
					}, duration);
					break;
				case 2:
					setTimeout(function() {
						uni.navigateTo({
							url: url,
						})
					}, duration);
					break;
				case 3:
					setTimeout(function() {
						uni.navigateBack({
							delta: parseInt(url),
						})
					}, duration);
					break;
				case 4:
					setTimeout(function() {
						uni.reLaunch({
							url: url,
						})
					}, duration);
					break;
				case 5:
					setTimeout(function() {
						uni.redirectTo({
							url: url,
						})
					}, duration);
					break;
			}
		} else if (typeof url == 'function') {
			setTimeout(function() {
				url && url();
			}, duration);
		} else {
			setTimeout(function() {
				uni.navigateTo({
					url: url,
				})
			}, title ? duration : 0);
		}
	}
}

/**
 * 处理服务器扫码带进来的参数
 * @param string param 扫码携带参数
 * @param string k 整体分割符 默认为：&
 * @param string p 单个分隔符 默认为：=
 * @return object
 */
const getUrlParams = (param, k, p) => {
	if (typeof param != 'string') return {}
	k = k ? k : '&'; //整体参数分隔符
	p = p ? p : '='; //单个参数分隔符
	var value = {}
	if (param.indexOf(k) !== -1) {
		param = param.split(k)
		for (var val in param) {
			if (param[val].indexOf(p) !== -1) {
				var item = param[val].split(p)
				value[item[0]] = item[1]
			}
		}
	} else if (param.indexOf(p) !== -1) {
		var item = param.split(p)
		value[item[0]] = item[1]
	} else {
		return param
	}
	return value
}

export default {
	Toast,
	getUrlParams,
}
